package com.chris.oauth2.web.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.chris.oauth2.Client;
import com.chris.oauth2.service.ClientService;

@Controller
public class LoginController {

	@Autowired
	ClientService clientService;

	@RequestMapping(value = { "login", "/" })
	public String login() {
		return "login/login";
	}

	@RequestMapping(value = { "logout", "/" })
	public ModelAndView logout(HttpSession session) {
		session.removeAttribute("client");
		session.removeAttribute("isAdmin");
		ModelAndView mav = new ModelAndView();
		mav.setViewName("forward:/login");
		return mav;
	}

	@RequestMapping("loginForm")
	public ModelAndView loginForm(HttpSession session, HttpServletRequest request, @RequestParam String username,
			@RequestParam String password, Model model) {
		ModelAndView mav = new ModelAndView();
		System.out.println("" + username + password);
		request.setAttribute("username", username);
		request.setAttribute("password", password);
		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
			mav.setViewName("forward:/login");
			return mav;
		}

		Client client = clientService.findByUsernameAndPassword(username, password);
		if (client == null) {
			mav.setViewName("forward:/login");
			return mav;
		}

		session.setAttribute("client", client);
		session.setAttribute("isAdmin", username.equals("admin"));
		mav.addObject("client", client);
		mav.setViewName("forward:/admin");
		return mav;
	}
}
